<script>
import axios from 'axios';

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://localhost:8080/api',
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器
api.interceptors.request.use(config => {
  // 确保请求头中包含正确的 Content-Type
  config.headers['Content-Type'] = 'application/json';
  return config;
});

// 添加响应拦截器
api.interceptors.response.use(
  response => response,
  error => {
    console.error('API Error:', error);
    return Promise.reject(error);
  }
);

export default {
  data() {
    return {
      blogs: [],
      currentPage: 1,
      count: 0,
      size: 10,
      editingBlog: null,
      showEditModal: false,
      loading: false
    }
  },
  methods: {
    async page(currentPage) {
      this.loading = true;
      try {
        const res = await api.get(`/blogs`, {
          params: {
            page: currentPage,
            size: this.size
          }
        });
        this.blogs = res.data.blogs;
        this.count = res.data.count;
        this.currentPage = currentPage;
      } catch (error) {
        console.error('获取博客列表失败:', error);
      } finally {
        this.loading = false;
      }
    },
    async editBlog(blog) {
      this.editingBlog = { ...blog };
      this.showEditModal = true;
    },
    async saveBlog() {
      try {
        await api.put(`/blogs/${this.editingBlog.id}`, this.editingBlog);
        await this.page(this.currentPage);
        this.showEditModal = false;
        alert('更新成功！');
      } catch (error) {
        console.error('更新失败:', error);
        alert('更新失败：' + error.message);
      }
    },
    async deleteBlog(id) {
      if (confirm('确定要删除这篇博客吗？')) {
        try {
          await api.delete(`/blogs/${id}`);
          await this.page(this.currentPage);
          alert('删除成功！');
        } catch (error) {
          console.error('删除失败:', error);
          alert('删除失败：' + error.message);
        }
      }
    }
  },
  mounted() {
    this.page(this.currentPage);
  }
}
</script>

<template>
  <div class="blog-container">
    <h1 class="page-title">博客列表</h1>
    
    <div class="blog-list" v-if="!loading">
      <article v-for="blog in blogs" :key="blog.id" class="blog-card">
        <div class="blog-header">
          <h2 class="blog-title">{{ blog.title }}</h2>
          <div class="blog-actions">
            <button @click="editBlog(blog)" class="btn edit-btn">
              <i class="fas fa-edit"></i> 编辑
            </button>
            <button @click="deleteBlog(blog.id)" class="btn delete-btn">
              <i class="fas fa-trash"></i> 删除
            </button>
          </div>
        </div>
        
        <p class="blog-description">{{ blog.description }}</p>
        <div class="blog-content">{{ blog.content }}</div>
        
        <div class="blog-meta">
          <span class="blog-date">发布时间: {{ formatDate(blog.created_at) }}</span>
          <span class="blog-status">状态: {{ blog.status === 1 ? '已发布' : '草稿' }}</span>
        </div>
      </article>
    </div>

    <div v-else class="loading-spinner">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <div class="pagination-info">
      第 {{ currentPage }} 页，每页 {{ size }} 篇，共 {{ count }} 篇
    </div>

    <!-- 编辑模态框 -->
    <div v-if="showEditModal" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <h2>编辑博客</h2>
          <button class="close-btn" @click="showEditModal = false">&times;</button>
        </div>
        
        <div class="modal-body">
          <div class="form-group">
            <label>标题</label>
            <input type="text" v-model="editingBlog.title" class="form-input">
          </div>
          
          <div class="form-group">
            <label>描述</label>
            <input type="text" v-model="editingBlog.description" class="form-input">
          </div>
          
          <div class="form-group">
            <label>内容</label>
            <textarea v-model="editingBlog.content" class="form-textarea"></textarea>
          </div>
        </div>
        
        <div class="modal-footer">
          <button @click="showEditModal = false" class="btn cancel-btn">取消</button>
          <button @click="saveBlog" class="btn save-btn">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.blog-container {
  padding: 2rem;
}

.page-title {
  font-size: 2rem;
  color: #2c3e50;
  margin-bottom: 2rem;
}

.blog-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 1.5rem;
  margin-bottom: 1.5rem;
  transition: transform 0.2s ease;
}

.blog-card:hover {
  transform: translateY(-2px);
}

.blog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.blog-title {
  font-size: 1.5rem;
  color: #2c3e50;
  margin: 0;
}

.blog-description {
  color: #666;
  margin-bottom: 1rem;
}

.blog-content {
  color: #2c3e50;
  line-height: 1.6;
  margin-bottom: 1rem;
}

.blog-meta {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 0.9rem;
}

.btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.edit-btn {
  background-color: #4CAF50;
  color: white;
  margin-right: 0.5rem;
}

.delete-btn {
  background-color: #f44336;
  color: white;
}

.edit-btn:hover {
  background-color: #45a049;
}

.delete-btn:hover {
  background-color: #da190b;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 1rem;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body {
  padding: 1rem;
}

.modal-footer {
  padding: 1rem;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.form-textarea {
  height: 200px;
  resize: vertical;
}

.save-btn {
  background-color: #4CAF50;
  color: white;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
}

/* 加载动画 */
.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.pagination-info {
  text-align: center;
  color: #666;
  margin-top: 1rem;
}

.blog-date {
  color: #666;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
}

.blog-date::before {
  content: '📅';
  margin-right: 0.5rem;
}
</style>